package utils

type Listener_CallBack func(sender interface{}, args ...interface{})

type IListenerOpera interface {
	AddListener(groupid, id interface{}, ls Listener_CallBack)
	RemoveListener(groupid, id interface{})
}

type Dispatch struct {
	id  interface{}
	lst GSyncMapGroup
}

func NewDispatch(id interface{}) *Dispatch {
	rval := &Dispatch{id: id}
	return rval
}

/*
**

	回调
*/
func (this *Dispatch) AddListener(id interface{}, ls Listener_CallBack) {
	this.lst.Set(id, ls)
}

func (this *Dispatch) RemoveListener(id interface{}) bool {
	return this.lst.RemoveEx(id)
}

func (this *Dispatch) Count() int {
	return this.lst.Count()
}

func (this *Dispatch) Dispatch(sender interface{}, args ...interface{}) int {
	n := 0
	this.lst.Range(func(key, value interface{}) bool {
		fn := value.(Listener_CallBack)
		fn(sender, args...)
		n++
		return true
	})
	return n
}

var (
	displst = NewDispatchList()
)

type DispatchList struct {
	lst GSyncMapGroup
}

func NewDispatchList() *DispatchList {
	rval := &DispatchList{}
	return rval
}

func (this *DispatchList) CheckGetDispatch(groupid interface{}) *Dispatch {
	val := this.lst.LoadOrStoreFunc(groupid, func() interface{} {
		return NewDispatch(groupid)
	}, nil).(*Dispatch)
	return val
}

func (this *DispatchList) FindDispatch(groupid interface{}) *Dispatch {
	val := this.lst.Get(groupid, nil)
	if val == nil {
		return nil
	}
	return val.(*Dispatch)
}

func (this *DispatchList) DispatchData(groupid interface{}, sender interface{}, args ...interface{}) int {
	val := this.FindDispatch(groupid)
	if val == nil {
		return 0
	}
	return val.Dispatch(sender, args...)
}

func CheckGetDispatch(groupid interface{}) *Dispatch {
	return displst.CheckGetDispatch(groupid)
}

func FindDispatch(groupid interface{}) *Dispatch {
	return displst.FindDispatch(groupid)
}

func DispatchData(groupid interface{}, sender interface{}, args ...interface{}) int {
	return displst.DispatchData(groupid, sender, args...)
}
